package com.jin.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jin.model.dto.WechatSessionResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信服务类
 */
@Slf4j
@Service
public class WechatService {
    
    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String appSecret;
    
    private final RestTemplate restTemplate;
    
    private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    
    public WechatService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    /**
     * 通过code获取微信用户session信息
     */
    public WechatSessionResponse code2Session(String code) {
        try {
            String url = UriComponentsBuilder.fromHttpUrl(CODE2SESSION_URL)
                    .queryParam("appid", appId)
                    .queryParam("secret", appSecret)
                    .queryParam("js_code", code)
                    .queryParam("grant_type", "authorization_code")
                    .toUriString();

            log.info("Calling WeChat code2session API with URL: {}", url);
            log.info("AppId: {}, Secret: {}, Code: {}", appId, appSecret != null ? "***" + appSecret.substring(appSecret.length()-4) : "null", code);

            // 使用 ResponseEntity 来获取原始响应
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String responseBody = responseEntity.getBody();

            log.info("WeChat API response: {}", responseBody);

            if (responseBody == null || responseBody.trim().isEmpty()) {
                log.error("WeChat API returned empty response");
                return null;
            }

            // 手动解析 JSON 响应
            ObjectMapper objectMapper = new ObjectMapper();
            WechatSessionResponse response = objectMapper.readValue(responseBody, WechatSessionResponse.class);

            if (response != null && response.isSuccess()) {
                log.info("WeChat code2session success, openId: {}", response.getOpenId());
                return response;
            } else {
                log.error("WeChat code2session failed: {}", response != null ? response.getErrMsg() : "Unknown error");
                return null;
            }
        } catch (Exception e) {
            log.error("Error calling WeChat code2session API", e);
            return null;
        }
    }
}
